package com.sunrise.xdoc.event;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;

import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;

import org.apache.commons.lang3.ClassUtils;

/**
 * @author PhanHongPhuc
 */
@ManagedBean
@ApplicationScoped
public class EventManager {

	public static void fireEvent(String eventName, EventData eventData) {
		Collection<Object> sessionBeans = FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
				.values();
		for (Object bean : sessionBeans) {
			Class<?> clazz = bean.getClass();
			for (Method m : clazz.getMethods()) {
				if (m.getAnnotation(ListenerMethod.class) != null && m.getParameterTypes().length == 2
						&& ClassUtils.isAssignable(m.getParameterTypes()[0], EventData.class)) {
					for (String en : m.getAnnotation(ListenerMethod.class).acceptedEvents()) {
						if (en.equals(eventName)) {
							try {
								// TODO call a function on the listener
								// sometimes cost the time to load data.
								// Consider to create thread to process the
								// event.
								m.invoke(bean, eventData, eventName);
								return;
							} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
				}
			}
		}
	}
}
